﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Infrastructure
{

    public interface IState
    {
    }

    public class State : IState
    {

        private readonly Dictionary<String, Transition> _transitions = new Dictionary<String, Transition>();

        public State(string name)
        {
            this.Name = name;
        }

        public string Name { get; private set; }

        public Dictionary<String, Transition> Transitions
        {
            get
            {
                return _transitions;
            }
        }

        public void AddTransition(Type @event, State state)
        {
            _transitions.Add(@event.Name,
                new Transition(@event, state));
        }

        public State GetNextStateBasedOn(Type @event)
        {
            Transition transition;
            State nextState;

            if (!this._transitions.
                TryGetValue(@event.Name, out transition) == true)
                throw new ApplicationException(
                    string.Format(
                    "The event {0} is not allowed when in a State of {1}", @event.Name, this.Name));

            if (!StateMachine.States.TryGetValue(transition.TargetState.Name, out nextState))
                throw new ApplicationException(
                    string.Format(
                    "The {0} state does not exist in the State Machine", transition.TargetState.Name));

            return transition.TargetState;
        }
    }
}
